package com.nongcai159.mall.lib_common.utils

import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import android.support.v4.content.FileProvider
import java.io.File

/**
 * 适配android7.0行为变更
 *
 *
 * Created by tanbiheng on 2017/10/26.
 */

object FileProvider {
    private val authority = "com.nongcai159.mall.fileProvider"

    /**
     * 获取文件Uri
     *
     * @param context
     * @param file
     * @return
     */
    fun getFileUri(context: Context, file: File): Uri? {
        var fileUri: Uri? = null
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            fileUri = getNFileUri(context, file)
        } else {
            fileUri = Uri.fromFile(file)
        }
        return fileUri
    }

    /**
     * android7.0 获取文件Uri
     *
     * @param context
     * @param file
     * @return
     */
    private fun getNFileUri(context: Context, file: File): Uri {
        return FileProvider.getUriForFile(context,
                authority,
                file)
    }

    /**
     * 根据Uri返回文件绝对路径
     * 兼容了file:///开头的 和 content://开头的情况
     */
    fun getRealFilePathFromUri(context: Context, uri: Uri?): String? {
        if (null == uri) return null
        val scheme = uri.scheme
        var data: String? = null
        if (scheme == null) {
            data = uri.path
        } else if (ContentResolver.SCHEME_FILE.equals(scheme, ignoreCase = true)) {
            data = uri.path
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme, ignoreCase = true)) {
            val cursor = context.contentResolver.query(uri, arrayOf(MediaStore.Images.ImageColumns.DATA), null, null, null)
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    val index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
                    if (index > -1) {
                        data = cursor.getString(index)
                    }
                }
                cursor.close()
            }
        }
        return data
    }

    /**
     * @param context
     * @param intent
     * @param type
     * @param file
     * @param writeAble
     */
    fun setIntentDataAndType(context: Context, intent: Intent, type: String,
                             file: File, writeAble: Boolean) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setDataAndType(getFileUri(context, file), type)
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            if (writeAble) {
                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
            }
        } else {
            intent.setDataAndType(Uri.fromFile(file), type)
        }
    }
}
